const fs = require('fs')
const path = require('path')
const rd = require('rd')
const glob = require('glob')
const superagent = require('superagent')
const { resolve, prefix, getToken,isPc } = require('./utils')

const themeDir = resolve('src/components')
const adminThemeDir = resolve('src/admins')
const typeEnum = ['components', 'admins']

function getComponents(type) {
  const regDir = resolve('src', type)

  if (!fs.existsSync(regDir)) {
    return []
  }

  const files = glob.sync(`${regDir}/**/index.vue`)

  return files.map(file => {
    const componentPath = path.relative(regDir, file)
      .replace(/\\/g, '/')
      .replace('/index.vue', '')
    const componentName = componentPath.replace(/^.*\//, '')
    const componentUpperName = componentName
      .replace(/-(\w)/g, (match, $1) => $1.toUpperCase())

    return {
      path: componentPath,
      name: componentName,
      upperName: componentUpperName
    }
  })
}

async function publish(name, token) {
  // console.info('正在发布组件:', name)

  var themePath = path.join(themeDir, name)

  if (!fs.existsSync(themePath)) {
    themePath = path.join(adminThemeDir, name)
    if (!fs.existsSync(themePath)) {
      console.log('上传组件不存在！')
      return
    }
  }

  const pattern = /.(vue|js|json|scss)$/
  const files = rd.readFileFilterSync(themePath, pattern)

  if (!files.length) {
    console.log('组件为空！')
    return
  }

  const queue = files.map(file => {
    return new Promise((reslove, reject) => {
      fs.readFile(file, (err, data) => {
        if (err) reject(err)
        reslove({
          path: path.relative(resolve(), file),
          content: data.toString()
        })
      })
    })
  })

  const filesData = await Promise.all(queue)
  const res = await superagent
    .post('/Site5ug/Publish', {
      loginInput:token,
      codeType: isPc ? 2 : 1,
      key: name,
      files: filesData
    })
    .use(prefix)

  const { status, message } = res.body

  if (status !== 1) {
    console.error(message)
    return
  }
}

module.exports = async name => {
  const token = getToken()
  if (!token) return

  if (name !== 'all') {
    publish(name, token)
    return
  }
  console.info('发布所有组件')
  let totalCount = 0
  let allPaths=[]
  typeEnum.forEach(type => {
    getComponents(type).forEach(component => {
      var count=0
      for(var i=0;i<component.path.length;i++){
        if(component.path[i]==='/'){
          count++
        }
      }
      if(count<=1){
        totalCount++
        //  await publish(component.path, token)
        allPaths.push(component.path)
      }
    })
  })

  for(var i=0;i<allPaths.length;i++){
    var path=allPaths[i]
    console.info('组件',path, '当前第'+i+'个')
    await publish(path, token)
  }
  
  await Promise.all([
    require('./admin')()
  ])

  console.log('批量提交成功,共提交' + totalCount + '个组件,数据并初始化成功')
}
